package com.common.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.util.AbstractFieldValueUtil;
import com.util.FormatUtil;
import com.util.UUIDHGenerator;

@Repository("baseDAO")
public class BaseDAOImpl<T> extends HibernateDaoSupport implements BaseDAO<T> {

	private static final Log LOG = LogFactory.getLog(BaseDAOImpl.class);

	@Resource(name = "sessionFactory")
	public void setMySessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	public boolean save(T t,String pkid) {
		boolean flag = false;
		try {
			Field[] fileds = t.getClass().getDeclaredFields();
			for (Field fs : fileds) {
				if (pkid==null){
					pkid="";
				}
				AbstractFieldValueUtil<T> fieldvalueutil = new AbstractFieldValueUtil<T>();
				if (pkid.equalsIgnoreCase(fs.getName())) {
					UUIDHGenerator uuid = new UUIDHGenerator();
					fieldvalueutil.setValueByParam(t, uuid.generate(), fs);
				}
				if ("ts".equalsIgnoreCase(fs.getName())) {
					Date date = new Date();
					String sdate = FormatUtil.getFormatTime(
							FormatUtil.FORMAT_THREE, date);// 拿到系统当前时间
					fieldvalueutil.setValueByParam(t, sdate, fs);
				}
				if ("dr".equalsIgnoreCase(fs.getName())) {
					fieldvalueutil.setValueByParam(t, 0, fs);
				}
			}
			getHibernateTemplate().save(t);
			flag = true;
		} catch (Exception ex) {
			LOG.info("保存" + t.getClass() + "出现异常:" + ex);
		}
		return flag;
	}

	public boolean saveOrUpdate(T t,String pkid) {
		boolean flag = false;
		try {
			Field[] fileds = t.getClass().getDeclaredFields();
			for (Field fs : fileds) {
				AbstractFieldValueUtil<T> aaa = new AbstractFieldValueUtil<T>();
				if (pkid==null){
					pkid="";
				}
				if (pkid.equalsIgnoreCase(fs.getName())) {
					String filedName = fs.getName();
					String firstLetter = filedName.substring(0, 1)
							.toUpperCase(); 
					String getMethodName = "get" + firstLetter
							+ filedName.substring(1); 
					Method getMethod = t.getClass().getMethod(getMethodName,
							new Class[] {});
					Object value = getMethod.invoke(fs, new Object[] {}); 
					if (value == null) {
						UUIDHGenerator uuid = new UUIDHGenerator();
						aaa.setValueByParam(t, uuid.generate(), fs);
					}
				}
				if ("ts".equalsIgnoreCase(fs.getName())) {
					Date date = new Date();
					String sdate = FormatUtil.getFormatTime(
							FormatUtil.FORMAT_THREE, date);// 拿到系统当前时间

					aaa.setValueByParam(t, sdate, fs);
				}

			}
			getHibernateTemplate().saveOrUpdate(t);
			flag = true;
		} catch (Exception ex) {
			LOG.info("保存或修改" + t.getClass() + "信息出现异常:" + ex);
		}
		return flag;
	}

	public boolean update(T t) {
		boolean flag = false;
		try {
			Field[] fileds = t.getClass().getDeclaredFields();
			for (Field fs : fileds) {
				AbstractFieldValueUtil<T> aaa = new AbstractFieldValueUtil<T>();
				if ("ts".equalsIgnoreCase(fs.getName())) {
					Date date = new Date();
					String sdate = FormatUtil.getFormatTime(
							FormatUtil.FORMAT_THREE, date);// 拿到系统当前时间

					aaa.setValueByParam(t, sdate, fs);
				}
			}
			getHibernateTemplate().update(t);
			flag = true;
		} catch (Exception ex) {
			LOG.info("修改" + t.getClass() + "出现异常:" + ex);
		}
		return flag;
	}

	public boolean update(String queryString, Object[] paramValue) {
		boolean flag = false;
		try {
			Query query = super.getSession().createQuery(queryString);
			for (int i = 0; i < paramValue.length; i++) {
				query.setParameter(i, paramValue[i]);
			}
			query.executeUpdate();
			flag = true;
		} catch (Exception ex) {
			LOG.info("修改数据时出错出现异常:" + ex);
		}
		return flag;
	}

	public boolean delete(T t) {
		boolean flag = false;
		try {
			getHibernateTemplate().delete(t);
			flag = true;
		} catch (Exception ex) {
			LOG.info("删除" + t.getClass() + "出现异常:" + ex);
		}
		return flag;
	}

	public boolean delete(Class<T> c, String id) {
		boolean flag = false;
		try {
			getHibernateTemplate().delete(getHibernateTemplate().get(c, id));
		} catch (Exception ex) {
			LOG.info("删除" + c.getClass() + "出现异常:" + ex);
		}
		return flag;
	}
	
	/**
	 * 
	  * 
	  * 
	  * @方法说明: 批量删除
	  * @param str
	  * @return
	  * @作者:徐龙
	  * @日期:2012-6-2
	 */
	@SuppressWarnings("unchecked")
	public boolean deleteByids(final String sql,final String[] strs) {
		return (Boolean) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						boolean flag = false;
						try {
								for (String str :strs) {
									String s = str.trim();
									SQLQuery query = session.createSQLQuery(sql);
									query.setString(0, s);
									query.executeUpdate();
								}
							flag = true;
						} catch (HibernateException e) {
							e.printStackTrace();
							LOG.info("批量删除："+e);
						}
						return flag;
					}

				});

	}
	

	@SuppressWarnings("unchecked")
	public List<T> find(String queryString, Object paramValue) {
		return getHibernateTemplate().find(queryString, paramValue);
	}

	public boolean delete(String queryString, Object[] paramValue) {
		boolean flag = false;
		try {
			Query query = super.getSession().createQuery(queryString);
			for (int i = 0; i < paramValue.length; i++) {
				query.setParameter(i, paramValue[i]);
			}
			query.executeUpdate();
			flag = true;
		} catch (Exception ex) {
			LOG.info("删除对象数据时出现异常:" + ex);
		}
		return flag;
	}

	public T get(Class<T> c, String id) {
		T t = null;
		try {
			t = (T) getHibernateTemplate().get(c, id);
		} catch (Exception ex) {
			LOG.info("通过ID查询" + c.getName() + "信息出现异常:" + ex);
		}
		return t;
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String queryString) {
		List<T> lt = null;
		try {
			lt = getHibernateTemplate().find(queryString);
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String queryString, Object[] paramValue) {
		List<T> lt = null;
		try {
			lt = getHibernateTemplate().find(queryString, paramValue);
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	@SuppressWarnings("unchecked")
	public List<T> findByNamedParam(String queryString, String[] paramName,
			Object[] paramValue) {
		List<T> lt = null;
		try {
			lt = getHibernateTemplate().findByNamedParam(queryString,
					paramName, paramValue);
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String queryString, int first, int len) {
		List<T> lt = null;
		try {
			Query query = super.getSession().createQuery(queryString);
			if (len != 0) {
				query.setFirstResult(first).setMaxResults(len);
			}
			lt = query.list();
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String queryString, Object[] paramValue, int first,
			int len) {
		List<T> lt = null;
		try {
			Query query = super.getSession().createQuery(queryString);
			for (int i = 0; i < paramValue.length; i++) {
				query.setParameter(i, paramValue[i]);
			}
			if (len != 0) {
				query.setFirstResult(first).setMaxResults(len);
			}
			lt = query.list();
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	public List<T> find(String queryString, String paramName,
			Object paramValue, int first, int len) {
		return this.findByNamedParam(queryString, new String[] { paramName },
				new Object[] { paramValue }, first, len);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByNamedParam(String queryString, String[] paramName,
			Object[] paramValue, int first, int len) {
		List<T> lt = null;
		try {
			Query query = super.getSession().createQuery(queryString);
			for (int i = 0; i < paramName.length; i++) {
				query.setParameter(paramName[i], paramValue[i]);
			}
			if (len != 0) {
				query.setFirstResult(first).setMaxResults(len);
			}
			lt = query.list();
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息出现异常:" + he);
		}
		return lt;
	}

	public Long getCount(String queryString) {
		Long count = 0L;
		try {
			Query query = super.getSession().createQuery(queryString);
			count = (Long) query.uniqueResult();
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息的条数出现异常:" + he);
		}
		return count.longValue();
	}

	public Long getCount(String queryString, Object paramValue) {
		return (Long) this.find(queryString, paramValue).get(0);
	}

	public Long getCount(String queryString, Object[] paramValue) {
		return (Long) this.find(queryString, paramValue).get(0);
	}

	public Long getCount(String queryString, String[] paramName,
			Object[] paramValue) {
		Long count = 0L;
		try {
			Query query = super.getSession().createQuery(queryString);
			for (int i = 0; i < paramName.length; i++) {
				query.setParameter(paramName[i], paramValue[i]);
			}
			count = (Long) query.uniqueResult();
		} catch (HibernateException he) {
			LOG.info("通过查询语句" + queryString + "查询信息的条数出现异常:" + he);
		}
		return count;
	}

	public Long getCount(Class<T> c) {
		String queryString = "select count(*) from " + c.getName()
				+ " as ct where ct.dr=0";
		return this.getCount(queryString);
	}

	public boolean symbolDelete(Class<T> c, String id) {
		boolean flag = false;
		T t=getHibernateTemplate().get(c, id);
		
		String hql = "update " + c.getName() + " set dr = 1 where id=:id";
		try {
			Query query = super.getSession().createQuery(hql);
			
			query.executeUpdate();
			flag = true;
		} catch (HibernateException he) {
			LOG.info("修改DR为１" + hql + "数出现异常:" + he);
		}
		return flag;
	}



}
